import { onUnmounted, ref, watchEffect } from 'vue'
import { defineStore } from 'pinia'
import { getIndex, setValue } from '@/common/utils'
import { getMeting } from '@/common/http.api'
import { usePlayerStore } from '@/stores/player'
import { PASE_SIZE } from '@/common/constant'

// 按需导出 useSongListStore
export const useSongListStore = defineStore(
  'songList',
  () => {
    // 获取 播放器 数据和方法
    const playerStore = usePlayerStore()

    // 歌单信息
    const playlistInfo = ref({})
    // 歌曲总数据
    const songList = ref([])
    // 每一页显示歌曲数据列表, 每页显示20条
    const limitSongList = ref([])
    // 总页数
    const totalPage = ref(0)
    // 页数
    const pageNum = ref(0)
    // 加载
    const loading = ref(false)
    // 是否还有更多数据
    const noMore = ref(false)
    // 加载更多状态
    const loadStatus = ref('loadmore')

    /**
     * 获取歌曲接口数据
     * @param {*} id
     */
    const getSongList = async (id) => {
      // 显示加载
      setValue({ target: loading, value: true })
      // 获取数据
      let info = await getMeting(id)
      // 根据接口设置列表数据
      let list = {}
      // #ifdef H5
      list = info.tracks
      // #endif
      // #ifdef MP
      info = info.results[0]
      list = info.List
      // #endif
      // 添加是否播放开关
      const newList = list.map((song) => {
        return Object.assign({}, song, {
          id: song.id ? parseInt(song.id) : song.rid,
          addQueue: false,
        })
      })
      // 设置值
      setValue([
        { target: playlistInfo, value: info },
        { target: totalPage, value: Math.floor(newList.length / PASE_SIZE) },
        { target: songList, value: newList },
        {
          target: limitSongList,
          value: Array.from(newList).slice(pageNum * PASE_SIZE, PASE_SIZE),
        },
        { target: loading, value: false },
      ])
    }

    /**
     * 加载更多数据
     */
    const getLimitSongList = () => {
      setValue({ target: loadStatus, value: 'loading' })

      if (loadStatus.value === 'loading') {
        if (pageNum.value < totalPage.value - 1) {
          pageNum.value += 1
          const nextPageIdx = pageNum.value * PASE_SIZE
          const nextSongList = Array.from(songList.value).slice(
            nextPageIdx,
            nextPageIdx + PASE_SIZE
          )

          const time = setTimeout(() => {
            limitSongList.value.push(...nextSongList)
            setValue({ target: loadStatus, value: 'loadmore' })
            clearTimeout(time)
          }, 500)
        } else if (pageNum.value >= totalPage.value - 1) {
          setValue([
            { target: loadStatus, value: 'nomore' },
            { target: noMore, value: true },
          ])
        }
      } else if (loadStatus.value === 'nomore')
        setValue({ target: noMore, value: false })
    }

    /**
     * 设置页面初始状态
     */
    const setPageStatus = () => {
      setValue([
        { target: playlistInfo, value: {} },
        { target: limitSongList, value: [] },
        { target: pageNum, value: 0 },
        { target: noMore, value: false },
      ])
    }

    const updateStatus = (id, status, type = 0) => {
      if (limitSongList.value.length > 0) {
        limitSongList.value.forEach((song) => {
          if (id === song.id) {
            if (type === 0) song.addQueue = status
            else if (type === 1) song.like = status
          }
        })
      }
    }

    // 监听-添加标识
    const stopWatch = watchEffect(
      () => {
        limitSongList.value.forEach((song) => {
          // 获取队列索引
          const curQueueIdx = getIndex(playerStore.playerQueue, song.id)
          // 获取歌曲喜欢索引
          const curSongLikeIdx = getIndex(
            playerStore.playerCollect.songlist,
            song.id
          )
          // 设置播放标识
          song.addQueue = curQueueIdx > -1
          // 设置收藏歌曲标识
          song.like = curSongLikeIdx > -1
        })
      },
      { flush: 'post' } // 在组件渲染之后执行副作用函数
    )

    // 停止侦听器
    onUnmounted(() => stopWatch())

    return {
      loading,
      totalPage,
      pageNum,
      noMore,
      loadStatus,
      playlistInfo,
      songList,
      limitSongList,
      setPageStatus,
      updateStatus,
      getSongList,
      getLimitSongList,
    }
  },
  {
    persist: true, // 开启后对 state 的数据读写都将持久化
  }
)
